<template lang="html">
  <section class="components-common_register_panel">
    <div class="panel-container" @click.stop="$emit('current')">
      <i class="ic-close" @click="$emit('hidePannel')"></i>
      <header class="panel-header">
        <h1>欢迎你开设训练营</h1>
        <p>马上等级讯息，提交开营</p>
      </header>
      <div class="panel-content">
        <ListItem
          :name="'court'"
          :title="'场地'"
          :defaultIndex="0"
          :dist="stores"
          v-on:dispatchValue="catchValue"
        ></ListItem>
        <InputItem
          :name="'desc'"
          :title="'内容'"
          :placeHolder="'请输入任意字符'"
          :errMsg="'请填写课程内容'"
          :regExp="/^.*$/"
          v-on:dispatchValue="catchValue"
        ></InputItem>
        <DateItem
          :name="'startpoint'"
          :title="'开始时间'"
          v-on:dispatchValue="catchValue"
        ></DateItem>
        <DateItem
          :name="'endpoint'"
          :title="'结束时间'"
          v-on:dispatchValue="catchValue"
        ></DateItem>
        <SelectItem
          :name="'gender'"
          :title="'性别'"
          :defaultIndex="0"
          :dist="genderDist"
          :multiSelect="true"
          v-on:dispatchValue="catchValue"
        ></SelectItem>
        <SelectItem
          :name="'position'"
          :title="'训练对象'"
          :defaultIndex="0"
          :dist="positionDist"
          :multiSelect="true"
          v-on:dispatchValue="catchValue"
        ></SelectItem>
        <button type="button" class="content-submitBtn" @click="submitContext">提交</button>
      </div>
    </div>
  </section>
</template>

<script>
import utils from '@/lib/utils'
import panel from './panel'

import superagent from 'superagent'
import authMiddleware from '@/lib/auth-middleware'

// let component
//
// let formChain = {
//   //检验表单内容是否完成
//   isFormCompleted(){
//     for(let k in this){
//       if(this[k].toString() === ''){
//         return false
//       }
//     }
//     return this
//   },
//   //格式化表单内容
//   formatingForm(){
//     if(typeof this.court === 'number'){
//       this.court = component.stores[this.court].id
//     }
//     if(utils.isArray(this.position)){
//       let positions = this.position.map(item => component.positionDist[item].id)
//       this.position = positions.toString()
//     }
//     if(utils.isArray(this.gender)){
//       let genders = this.gender.map(item => component.genderDist[item].id)
//       this.gender = genders.toString()
//     }
//     return this
//   },
//   validateForm(){
//     if(this.startpoint >= this.endpoint){
//       utils.toast('结束时间必须大于开始时间')
//       return false
//     }
//     return this
//   },
// }

export default {
  name: 'ApplyPannel',
  mixins: [
    panel
  ],
  props: {
    stores: {
      type: Array,
      required: true
    },
  },
  data(){
    return {
      applyInfo: {
        court: '',//ListItem只传回dist中的index
        desc: '',
        startpoint: '',
        endpoint: '',
        gender: '',
        position: ''
      }
    }
  },
  components: {
    DateItem: require('./component/date'),
  },
  methods: {
    catchValue(payload){
      this.applyInfo = Object.assign({}, this.applyInfo, { [payload.key]: payload.value })
    },
    //检验表单内容是否完成
    isFormCompleted(form){
      for(let k in form){
        if(form[k].toString() === ''){
          return false
        }
      }
      return true
    },
    //检查表单内容
    validateForm(form){
      if(form.startpoint <= Date.now()/1000){
        utils.toast('开始时间必须大于当前时间')
        return false
      }
      if(form.startpoint >= form.endpoint){
        utils.toast('结束时间必须大于开始时间')
        return false
      }
      return true
    },
    //格式化表单内容
    formatingForm(form){
      if(typeof form.court === 'number'){
        form.court = this.stores[form.court].id
      }
      if(utils.isArray(form.position)){
        let positions = form.position.map(item => this.positionDist[item].id)
        form.position = positions.toString()
      }
      if(utils.isArray(form.gender)){
        let genders = form.gender.map(item => this.genderDist[item].id)
        form.gender = genders.toString()
      }
      return form
    },
    extraForm(form){
      return {
        storeId: form.court,
        gender: form.gender,
        position: form.position,
        content: form.desc,
        // startTime: 1201250220,
        // endTime: 1201250330
        startTime: form.startpoint,
        endTime: form.endpoint
      }
    },
    postForApply(params){
      return new Promise((resolve, reject) => {
        superagent.post('/api/requesition/applyNewSubject')
          .type('form-data')
          .send(params)
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok && res.body){
              resolve(res.body.data)
            } else {
              if(res.body.data && res.body.data.errMsg){
                reject(res.body.data.errMsg)
              } else {
                reject(new Error(`request:postForApply error`))
              }
            }
          })
      })
      // return utils.requestFactory({
      //   url: '/api/requesition/applyNewSubject',
      //   type: 'post',
      //   params
      // })
    },
    submitContext(){
      let isCompleted = this.isFormCompleted(this.applyInfo)
      if(!isCompleted){
        utils.toast('请完整填写表单内容')
        return
      }
      if(!this.validateForm(this.applyInfo)){
        return
      }
      let form = this.formatingForm(this.applyInfo),
          params = this.extraForm(form)

      this.postForApply(params)
      .then(data => {
        this.$emit('hidePannel')
        utils.modal({
          title: '申请成功！',
          desc: 'Z Plus平台客服将稍后联系您'
        })
      })
      .catch(e => {
        if(utils.isArray(e)){
          let content = e.reduce((pre, next) => {
            return `${pre}<br>${next}`
          })
          utils.modal({
            title: '表单内容有误！',
            desc: content
          })
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped src="./panel.scss"></style>
